package rtsp_server

import (
	"context"

	"github.com/bluenviron/gortsplib/v3"
	"github.com/bluenviron/gortsplib/v3/pkg/formats"
	"github.com/bluenviron/gortsplib/v3/pkg/media"
	"github.com/pion/rtp"
)

type session struct {
	path    string
	ctx     context.Context
	ctxFunc context.CancelFunc

	stream    *gortsplib.ServerStream
	publisher *gortsplib.ServerSession
}

func newSession(ctx *gortsplib.ServerHandlerOnAnnounceCtx) *session {
	mCtx, mCtxFunc := context.WithCancel(context.Background())
	return &session{
		ctx:       mCtx,
		ctxFunc:   mCtxFunc,
		path:      ctx.Path,
		stream:    gortsplib.NewServerStream(ctx.Medias),
		publisher: ctx.Session,
	}
}

func (tis *session) OnRecord(ctx *gortsplib.ServerHandlerOnRecordCtx) {
	// called when receiving a RTP packet
	ctx.Session.OnPacketRTPAny(func(medi *media.Media, forma formats.Format, pkt *rtp.Packet) {
		_ = tis.stream.WritePacketRTP(medi, pkt)
	})
}

func (tis *session) Close() {
	_ = tis.stream.Close()
	tis.ctxFunc()
}
